# coding=utf-8

from flask_mail import Message, current_app
from threading import Thread

from app.extensions import mail


def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)


def send_email(subject, sender, recipients, text_body=None, html_body=None, async_send=True):
    msg = Message(subject=subject, sender=sender, recipients=recipients, body=text_body, html=html_body)
    if async_send:
        app = current_app._get_current_object()  # 获取被代理的真实对象
        t = Thread(target=send_async_email, args=(app, msg))
        t.start()
    else:
        mail.send(msg)
